package com.example.mall_image_server.controller;

import com.example.mall_image_server.service.LocalFileUploadServiceImpl;
import com.example.mall_image_server.utils.FileMd5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class FileUploadController {
    @Autowired
    @Qualifier(value = "localFileUploadServiceImpl")
    private LocalFileUploadServiceImpl fileUploadService;

    @RequestMapping("/upload/image")
    @ResponseBody
    public Map<String, Object> handleSingleImageUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            throw new RuntimeException("文件为空");
        }

        String url = fileUploadService.saveImage(file);

        // result
        if ("".equals(url)) {
            Map<String, Object> result = new HashMap<>();
            result.put("message", "fail");
            result.put("data", null);
            result.put("code", 9999);
            return result;
        } else {
            Map<String, String> data = new HashMap<>();
            data.put("url", url);
            Map<String, Object> result = new HashMap<>();
            result.put("message", "ok");
            result.put("data", data);
            result.put("code", 0);
            return result;
        }
    }

    @RequestMapping("/upload/images")
    @ResponseBody
    public Map<String,Object> handleMoreImageUpload(@RequestParam("file") MultipartFile[] files) {
        if (files.length == 0) {
            throw new RuntimeException("文件为空");
        }

        List<String> urls = fileUploadService.saveImages(files);
        List<String> filtered=urls.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
        if (filtered.size() == 0) {
            Map<String, Object> result = new HashMap<>();
            result.put("message", "fail");
            result.put("data", null);
            result.put("code", 9999);
            return result;
        } else {
            Map<String, Object> data = new HashMap<>();
            data.put("urls", filtered);
            Map<String, Object> result = new HashMap<>();
            result.put("message", "ok");
            result.put("data", data);
            result.put("code", 0);
            return result;
        }
    }
}
